import React,{useEffect,useState} from 'react'
import {useDispatch,useSelector} from 'react-redux'
import {getShopcartAsync,changeNumAsync} from '@/store/async/shopcartAsync'
import './ShopCart.scss'
export default function ShopCart() {
    const dispatch=useDispatch()
    const shopcartList=useSelector((state)=>{
      return state.shopcartKey.shopcartList
    })

    const getShopcartList=()=>{
        dispatch(getShopcartAsync)
    }
    const changeNum=(op,id,num)=>{
      switch(op){
        case '+':
          setTimeout(() => {
            dispatch(changeNumAsync({id,num}))
          }, 10);
          break
        case '-':
          if(num>=1){
            setTimeout(() => {
              dispatch(changeNumAsync({id,num}))
            }, 10);
          }else{
            alert('数量不能小于1')
          }
        
          break
      }
    }
    useEffect(()=>{
        getShopcartList()
    },[])
  return (
    <div>
        <table>
          <thead>
            <tr>
              <th>编号</th>
              <th>名称</th>
              <th>图片</th>
              <th>价格</th>
              <th>数量</th>
              <th>小计</th>
            </tr>
          </thead>
          <tbody>
            {
              shopcartList.map(item=><tr key={item.id}>
                <td>{item.id}</td>
                <td>{item.pname}</td>
                <td>
                  <img src={item.pic} alt=""  style={{width:'80px'}}/>
                </td>
                <td>{item.price}</td>
                <td>
                  <button onClick={()=>changeNum('-',item.id,item.num-1)}>-</button>
                  <input type='text' value={item.num} onChange={(e)=>{
                    dispatch(changeNumAsync({id:item.id,num:e.target.value}))
                  }}></input>
                  <button onClick={()=>changeNum('+',item.id,item.num+1)}>+</button>
                  </td>
                <td>{item.price*item.num}</td>
              </tr>)
            }
          </tbody>
        </table>
    </div>
  )
}
